<script setup>
import { ref, onMounted, provide, computed } from 'vue';
import * as THREE from 'three';

const wrapper = ref(null);
let scene = null;

const emits = defineEmits(['frameFunc']);

const props = defineProps({
  width: {
    type: Number,
    default: innerWidth,
  },
  height: {
    type: Number,
    default: innerHeight,
  },
  background: {
    type: String,
    default: 'black',
  },
  camera: Object,
});

const getCameraPosition = () => {
  const {
    x = 0,
    y = 0,
    z = 5,
  } = props.camera || {};
  return [x, y, z];
};

// 创建场景
scene = new THREE.Scene();
scene.background = new THREE.Color(props.background);
// scene props to do

provide( 'scene', scene );

const camera = new THREE.PerspectiveCamera(
  75,
  props.width / props.height,
  props.camera?.near || .1,
  props.camera?.far || 1000,
);
camera.position.set( ...getCameraPosition() );

// 渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize( props.width, props.height );

onMounted(() => {
  wrapper.value.appendChild( renderer.domElement );

  (function animate () {
    requestAnimationFrame( animate );
    camera.position.set( ...getCameraPosition() );
    emits('frameFunc', camera, scene, renderer);
    renderer.render( scene, camera );
  })();

});

</script>

<template>
  <div ref="wrapper">
    <slot />
  </div>
</template>
